package com.own.component.common.util;

import com.own.component.common.exception.BusinessException;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * FileMd5Util
 *
 * @author chenxueli
 * @date 2022-08-01 09:59:00
 */
@Slf4j
public class FileMd5Util {

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final MessageDigest MESSAGE_DIGEST;

    static {
        try {
            MESSAGE_DIGEST = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new BusinessException("初始化失败，MessageDigest不支持FileMd5Util");
        }
    }

    /**
     * 获取文件md5
     *
     * @param file 内容
     * @return md5
     */
    public static String get(File file) {
        try {
            @Cleanup
            var inputStream = new FileInputStream(file);
            var channel = inputStream.getChannel();
            var byteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MESSAGE_DIGEST.update(byteBuffer);
            return bufferToHex(MESSAGE_DIGEST.digest());
        } catch (IOException e) {
            log.error("获取文件md5失败：{}", e.getMessage());
            throw new BusinessException("获取文件md5失败");
        }
    }

    /**
     * 获取文件md5
     *
     * @param content 内容
     * @return md5
     */
    public static String get(String content) {
        return get(content.getBytes());
    }

    /**
     * 获取文件md5
     *
     * @param bytes 内容
     * @return md5
     */
    public static String get(byte[] bytes) {
        MESSAGE_DIGEST.update(bytes);
        return bufferToHex(MESSAGE_DIGEST.digest());
    }

    /**
     * 获取文件md5
     *
     * @param file 内容
     * @return md5
     */
    public static String get(MultipartFile file) {
        try {
            var uploadBytes = file.getBytes();
            var digest = MESSAGE_DIGEST.digest(uploadBytes);
            return new BigInteger(1, digest).toString(16);
        } catch (IOException e) {
            log.error("获取文件md5失败：{}", e.getMessage());
            throw new BusinessException("获取文件md5失败");
        }
    }

    private static String bufferToHex(byte[] bytes) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    @SuppressWarnings("all")
    private static String bufferToHex(byte[] bytes, int m, int n) {
        var buffer = new StringBuffer(2 * n);
        var k = m + n;
        for (var l = m; l < k; l++) {
            appendHexPair(bytes[l], buffer);
        }
        return buffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        var c0 = HEX_DIGITS[(bt & 0xf0) >> 4];
        var c1 = HEX_DIGITS[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

    public static boolean checkPassword(String password, String md5PwdStr) {
        return get(password).equals(md5PwdStr);
    }

}
